package logic

import (
	"context"
	"errors"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"order/model"
	"order/order"

	"order/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateStatusLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateStatusLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateStatusLogic {
	return &UpdateStatusLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}
func checkUpdateStatus(in *order.UpdateStatusRequest) error {
	if in.Id == 0 {
		return status.Error(codes.InvalidArgument, " id is required")
	}
	//if in.Status < 0 || in.Status > 4 {
	//	return status.Error(codes.InvalidArgument, " status is invalid")
	//}
	//if in.LogisticsStatus < 1 || in.LogisticsStatus > 5 {
	//	return status.Error(codes.InvalidArgument, " logisticsStatus is 1 - 5")
	//}
	return nil
}
func (l *UpdateStatusLogic) UpdateStatus(in *order.UpdateStatusRequest) (*order.UpdateStatusResponse, error) {
	// todo: add your logic here and delete this line
	if err := checkUpdateStatus(in); err != nil {
		return nil, err
	}

	//up := model.Db.Model(&model.OrderGoods{})
	var err error
	if (in.Status == 3 || in.Status == 4) && (in.LogisticsStatus >= 1 && in.LogisticsStatus <= 5) {
		err = model.Db.Model(&model.OrderGoods{}).Where("id = ?", in.Id).Updates(model.OrderGoods{Status: in.Status, LogisticsStatus: in.LogisticsStatus}).Error
	} else if in.Status == 3 || in.Status == 4 {
		err = model.Db.Model(&model.OrderGoods{}).Where("id = ?", in.Id).Update("status = ?", in.Status).Error
	} else if in.LogisticsStatus >= 1 && in.LogisticsStatus <= 5 {
		err = model.Db.Model(&model.OrderGoods{}).Where("id = ?", in.Id).Update("logistics_status = ?", in.LogisticsStatus).Error
	} else {
		return nil, status.Error(codes.InvalidArgument, "invalid parameter")
	}
	if err != nil {
		return nil, errors.New("修改失败 err:" + err.Error())
	}

	//orderGoodsModel, err := model.FindOrderGoodsById(in.Id)
	//if err != nil {
	//	return nil, err
	//}
	return &order.UpdateStatusResponse{}, nil
}
